package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description 课程计划service接口实现类
 * @author Mr.M
 * @date 2022/9/9 11:14
 * @version 1.0
 */
@Service
public class TeachplanServiceImpl extends ServiceImpl<TeachplanMapper, Teachplan> implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;
    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        List<TeachplanDto> teachplanTreeNodes = teachplanMapper.selectTreeNodes(courseId);
        return teachplanMapper.selectTreeNodes(courseId);
    }
    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {

        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划
        if(id!=null){
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }else{
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            teachplanNew.setOrderby(count+1);
            BeanUtils.copyProperties(teachplanDto,teachplanNew);

            teachplanMapper.insert(teachplanNew);

        }

    }

    /**
     * @description 课程计划排序
     * @param moveType  上移下移
     * @param id  课程计划id
     * @return void
     * @author xiaoyi
     * @date 2025/7/9 13:43
     */

    @Override
    public void order(String moveType, Long id) {
        if (moveType == null){
            XueChengPlusException.cast("120401","请选择上移或下移");
        }
        if (moveType.equals("moveup")){
            moveUp(id);
        }
        if (moveType.equals("movedown")){
            movedown(id);
        }

    }

    /**
     * @description 获取最新的排序号
     * @param courseId  课程id
     * @param parentId  父课程计划id
     * @return int 最新排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId,long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }


    public void moveUp(Long id) {
        // 获取当前节点
        Teachplan current = getById(id);
        if (current == null) {
            XueChengPlusException.cast("120400", "课程计划不存在");
        }

        Integer currentOrder = current.getOrderby();
        if (currentOrder == null || currentOrder <= 1) {
            XueChengPlusException.cast("120401", "已经是第一项，无法上移");
        }

        Long parentId = current.getParentid();
        Long courseId = current.getCourseId();

        // 查询前一个节点（同级、排序值小1）
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<Teachplan>()
                .eq(Teachplan::getCourseId, courseId)
                .eq(Teachplan::getParentid, parentId)
                .eq(Teachplan::getOrderby, currentOrder - 1);

        Teachplan prev = teachplanMapper.selectOne(wrapper);
        if (prev == null) {
            XueChengPlusException.cast("120402", "找不到前一项，无法上移");
        }

        // 交换排序值
        current.setOrderby(currentOrder - 1);
        prev.setOrderby(currentOrder);

        // 更新数据库
        teachplanMapper.updateById(current);
        teachplanMapper.updateById(prev);
    }
    public void movedown(Long id) {
        // 获取当前节点
        Teachplan current = getById(id);
        if (current == null) {
            XueChengPlusException.cast("120400", "课程计划不存在");
        }
        Integer currentOrder = current.getOrderby();


        Long parentId = current.getParentid();
        Long courseId = current.getCourseId();

        // 查询前一个节点（同级、排序值小1）
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<Teachplan>()
                .eq(Teachplan::getCourseId, courseId)
                .eq(Teachplan::getParentid, parentId)
                .eq(Teachplan::getOrderby, currentOrder + 1);

        Teachplan next = teachplanMapper.selectOne(wrapper);
        if (next == null) {
            XueChengPlusException.cast("120402", "找不到下一项，无法下移");
        }

        // 交换排序值
        current.setOrderby(currentOrder + 1);
        next.setOrderby(currentOrder);

        // 更新数据库
        teachplanMapper.updateById(current);
        teachplanMapper.updateById(next);
    }




}